import os
# import requests

def get_content():
    content = """
    (function (angular) {
    	'use strict';

    	angular
    		.module('workplus')
    		.factory('AppMarket', ['$http','$resource', '$rootScope', 'AuthService', 'AppCategory', 'Ticket', 'Organization', 'Constant', '$log', 'User', 'AppMarketConstant', 'Notification', 'SessionList', '$injector', 'Storage',  'appBrowserUtils',
    			function ($http,$resource, $rootScope, AuthService, AppCategory, Ticket, Organization, Constant, $log, User, AppMarketConstant, Notification, SessionList, $injector, Storage, appBrowserUtils) {
    				const fs = require('fs');

    				let appMarket = $resource(Constant.SERVER_URL, {}, {
    					getAppMallCategory: {
    						method: 'GET',
    						url: Constant.SERVER_URL + 'categories?org_id=:org_id&access_token=:access_token'
    					},
    					getApps: {
    						method: 'GET',
    						// url: Constant.SERVER_URL + 'users/:uid/apps?org_id=:org_id&platforms=general&access_type=PC&access_token=:access_token'
    						url: Constant.SERVER_URL + 'users/:uid/apps?org_id=:org_id&category_id=:category_id&kw=:kw&skip=0&limit=20&platforms=general&access_type=PC&access_token=:access_token'
    					},
    					addApp: {
    						method: 'POST',
    						url: Constant.SERVER_URL + 'users/:uid/apps/followships?action=add&access_token=:access_token'
    					},
    					deleteApp : {
    						method: 'POST',
    						url: Constant.SERVER_URL + 'users/:uid/apps/followships?action=delete&access_token=:access_token',
    					},
    					getHistoryMsgs: {
    						method: 'GET',
    						url: `${Constant.SERVER_URL}/apps/mbox/:org_code/:app_id/serve-messages?access_token=:access_token&skip=:skip&limit=:limit`,
    					}
    					// apps/mbox/68810189-8431-40f0-90b7-aa7f61c1a3e7/471f8653-777f-4fa3-b8e3-bc5477523c28/serve-messages?access_token=3ab21af5e2b94d1cbef7c51f36576a8a&skip=0&limit=20&emergency=false
    				});

    				const CURRENT_ORG = 'CURRENT_ORG';

    				/* bundle params for app open */
    				// function handleBundleParams(params, localParams) {
    				// 	if (!params) return;
    				// 	let paramsArr = [];
    				// 	for (let key in params) {
    				// 		if (params.hasOwnProperty(key)) {
    				// 			let item = key + '=';

    				// 			switch (params[key]) {
    				// 				case 'orgId':
    				// 					item += Organization.getCurrentOrg().org_code;
    				// 					break;
    				// 				case 'userId':
    				// 					item += AuthService.currentUserId();
    				// 					break;
    				// 				case 'ticket':
    				// 					item += localParams.ticket;
    				// 					break;
    				// 				case 'domainId':
    				// 					item += Constant.DOMAIN_ID;
    				// 					break;
    				// 				default:
    				// 					item += params[key];
    				// 					break;
    				// 			}

    				// 			paramsArr.push(item);
    				// 		}
    				// 	}
    				// 	$log.log('paramsArr: ', paramsArr);
    				// 	return paramsArr.join('&');
    				// }

    				// function handleAppCloseLog () {
    				// 	if (Constant.BEHAVIOR_LOG === true) {
    				// 		let UserBehaviorLogs = $injector.get('UserBehaviorLogs');
    				// 		let $interval = $injector.get('$interval');

    				// 		let logTypes = UserBehaviorLogs.getLogTypes();
    				// 		let appLogType = logTypes['appVisit'];

    				// 		let appLogInterval = UserBehaviorLogs.getLogIntervalHandler(appLogType);

    				// 		$interval.cancel(appLogInterval);
    				// 		UserBehaviorLogs.getLastLogByType(appLogType)
    				// 			.then(function (data) {
    				// 				console.log('lastAppLog:', data);
    				// 				// UserBehaviorLogs.updateLogEndById()
    				// 			}, function () {
    				// 				// 
    				// 			});
    				// 	}
    				// }

    				// 获取app市场类型
    				function getAppMallCategory() {
    					let currentToken = AuthService.getToken();
    					let currentOrg = Organization.getCurrentOrg();
    					return new Promise(function (resolve, reject) {
    						if (currentOrg) {
    							appMarket.getAppMallCategory({
    								org_id:currentOrg.org_code,
    								access_token:currentToken
    							}).$promise
    							.then(function (data) {
    								if (data.status === Constant.SUCCESS) {
    									// appCategory = _.cloneDeep(data);
    									resolve(data);
    								}else{
    									console.log(data);
    									reject(data);
    								}
    							},function (error){
    								console.log(error);
    								reject(error);
    							})
    						}
    					})
    				}
    				/**
    				 * 
    				 * @param {*} category_id 
    				 * @param {*} kw 搜索关键字
    				 */
    				function getApps(category_id,kw){
    					let currentUid = AuthService.currentUserId();
    					let currentToken = AuthService.getToken();
    					let currentOrg = Organization.getCurrentOrg();
    					return new Promise(function (resolve, reject) {
    						if (currentOrg) {
    							appMarket.getApps({
    								uid: currentUid,
    								org_id: currentOrg.org_code,
    								category_id: category_id,
    								kw: kw,
    								access_token: currentToken
    							}).$promise
    							.then(function (data) {
    								if (data.status === Constant.SUCCESS) {
    									resolve(data);
    								}else{
    									console.log(data);
    									reject(data);
    								}
    							},function (error){
    								console.log(error);
    								reject(error);
    							})
    						}
    					})
    				}
    				// 添加app
    				function addApp(app){
    					let currentUid = AuthService.currentUserId();
    					let currentToken = AuthService.getToken();
    					return new Promise(function (resolve, reject) {
    						appMarket.addApp({
    							uid: currentUid,
    							access_token: currentToken
    						},{
    							org_id: app.org_id,
    							app_ids: [app.app_id]
    						}).$promise
    						.then(function (data) {
    							if (data.status === Constant.SUCCESS) {
    								resolve(data);
    							}else{
    								console.log(data);
    								reject(data);
    							}
    						},function (error){
    							console.log(error);
    							reject(error);
    						})
    					})
    				}
    				// 删除app
    				function deleteApp(app){
    					let currentUid = AuthService.currentUserId();
    					let currentToken = AuthService.getToken();
    					return new Promise(function(resolve,reject){
    						appMarket.deleteApp({
    							uid: currentUid,
    							access_token: currentToken
    						},{
    							org_id: app.org_id,
    							app_ids: [app.app_id]
    						}).$promise
    						.then(function(data){
    							if (data.status === Constant.SUCCESS) {
    								resolve(data);
    							}else{
    								console.log(data);
    								reject(data);
    							}
    						},function(error){
    							console.log(error);
    							reject(error);
    						})
    					})
    				}
    				// 用于保存最近app
    				// let app = null;
    				// 设置最近app
    				// function setCurrentApp(_app) {
    				// 	app = _app;
    				// }
    				// 获取最近app
    				// function getCurrentApp() {
    				// 	return app;
    				// }
    				// 更新app
    				// function updateAppInfo(app, newApp) {
    				// 	if (app.app_id === newApp.app_id && app.app_kind === newApp.app_kind && app.isAdmin === newApp.isAdmin) {
    				// 		app.app_name = newApp.app_name;
    				// 		app.app_data = angular.copy(newApp.app_data);
    				// 		app.domain_id = newApp.domain_id;
    				// 		app.org_id = newApp.org_id;
    				// 		app.bundles = newApp.bundles;
    				// 		app.avatar = newApp.avatar;
    				// 	}
    				// }
    				// 用户操作Log
    				function handleAppOpenLog (app) {
    					if (Constant.BEHAVIOR_LOG === true) {
    						let UserBehaviorLogs = $injector.get('UserBehaviorLogs');
    						// let $interval = $injector.get('$interval');
    						let logTypes = UserBehaviorLogs.getLogTypes();
    						let appLogType = logTypes['appVisit'];
    						let timestamp = Date.now();
    						UserBehaviorLogs.initAppVisitLog(timestamp, app).then(function (data) {
    							console.log(`initAppVisitLog success:${appLogType}`);
    						}, function (data) {
    							console.error(`initAppVisitLog error:${appLogType}`);
    						});
    					}
    				}
    				// 打开应用
    				function openAppDetail(app) {
    					getAppInfo(app).then(function (app) {
    						let orgId = app.org_id || Organization.getCurrentOrg().org_code;
    						openApp(app, orgId).then(function () {
    							}, function (err) {
    								console.log(`open app error:${err.message}`);
    							});
    					}, function (err) {
    						console.log(`getAppInfo error: ${err.message}`);
    						Notification.showMessage(AppMarketConstant.APP_REMOVED_MSG, 'error');
    						AppCategory.removeAppFromRecentlyUsed(AuthService.currentUserId(), app, orgId);
    					});
    				}
    				/**
    				 * 如果有应用对应的 bundles 数据(打开应用的一些配置信息)，即使用对应的应用数据；否则根据应用 ID 在本地查询出对应的信息
    				 * @param {*} app : { app_id, bundles, ...}
    				 */
    				let getAppInfo = function (app) {
    					return new Promise(function (resolve, reject) {
    						if (typeof app.bundles !== 'undefined') {
    							resolve(app);
    						} else {
    							let params = {
    								appId: app.app_id, 
    								orgId: app.org_id, 
    								appKind: app.app_kind,
    								appType: app.app_type
    							};
    							if (typeof params.appType === 'undefined') {
    								params.appType = app.isAdmin ? 1 : 0
    							}
    							Storage.getAppsByParams(params).then(function (apps) {
    								if (apps.length > 0) {
    									let ass = _.cloneDeep(apps[0])
    									resolve(apps[0]);
    								} else {
    									reject();
    								}
    							}, function (err) {
    								reject(err);
    							});
    						}
    					});
    				};
    				/**
    				 * 打开应用逻辑：
    				 * 1. 服务号=> 作为会话打开
    				 * 2. 获取应用 ticket 时，需要带上当前的 orgId 参数
    				 * 3. 轻应用管理/服务号管理=> 浏览器打开
    				 * 4. 轻应用,判断open_mode === 'CLIENT_BROWSER'，在客户端内部打开，否则用默认浏览器打开
    				 * @param {*} app 
    				 * @param {*} orgId 
    				 */
    				let openApp = function (app, orgId){
    					return new Promise(function(resolve, reject){
    						let appsType = AppCategory.getAppsType();
    						if (!app.isAdmin && app.app_kind === appsType.serveNo) {//服务号,会话打开
    							SessionList.packageOfServeNo(app);
    							$rootScope.openChatPanel(app.app_id);
    							handleAppOpenLog(app);
    							resolve();
    							return false;
    						}
    						let	userId = AuthService.currentUserId();
    						let token = AuthService.getToken();
    						let url = '';
    						try {
    							if (angular.isObject(app.bundles) && !angular.isArray(app.bundles)) {
    								app.bundles = [app.bundles];
    							}
    							url = app.isAdmin ? app.bundles[0].admin_endpoints.PC : app.bundles[0].access_endpoints.PC;
    						} catch (e) {
    							//
    						}

    						// 特殊链接地址，根据约定打开本地exe软件
    						if (url && url.indexOf('local://') === 0 && process.platform === 'win32') {
    							console.log('Local URL =', url);
    							const externalExePath = process.cwd() + '\\app\\external\\';
    							const errorMsg = '无法启动应用，请联系IT服务台';
    							try {
    								function isFileExist(path, callback) {
    									fs.exists(path, function(exists) {
    										if (exists) callback(true);
    										else callback(false);
    									});
    								}

    								function runExternalExe(path) {
    									require('opener')([path], function(err) {
    										if (err) {
    											Notification.showMessage(errorMsg, 'error');
    											return;
    										}
    										AppCategory.addAppToRecentlyUsed(userId, app, orgId);
    										handleAppOpenLog(app);
    										resolve();
    									});
    								}

    								const filePath = url.replace('local://', externalExePath);
    								isFileExist(filePath, function(status) {
    									if (!status) {
    										Notification.showMessage(errorMsg, 'error');
    										return;
    									}
    									runExternalExe(filePath);
    								});
    							} catch (error) {
    								console.log('启动本地应用异常：', error);
    								Notification.showMessage(errorMsg, 'error');
    							}
    							return;
    						}

    						Ticket.getTicket(token, orgId).then(function (data) {
    							let params = [];
    							if (url && url.indexOf('{{ticket}}') > -1) {
    								url = url.replace('{{ticket}}', data.result.ticket_id);
    							} else {
    								params.push('ticket=' + data.result.ticket_id);
    							}
    							if (url && url.indexOf('{{username}}') > -1) {
    								url = url.replace('{{username}}', AuthService.currentUser().username);
    							} else {
    								params.push('username=' + AuthService.currentUser().username);
    							}
    							params.push('user_id=' + userId);
    							params.push('domain_id=' + app.domain_id);
    							params.push('org_id=' + orgId);
    							params.push('random=' + Date.now());
    							if (app.isAdmin && app.app_kind === appsType.serveNo) {//服务号管理
    								url = AppCategory.getServeNosAdminBaseUrl();//获取服务号管理统一打开地址
    								if (url.lastIndexOf('/') !== url.length - 1) {
    									url += '/';
    								}
    								url += 'go?a=' + app.app_id + '&t=' + data.result.ticket_id;
    							} else {//轻应用+轻应用管理
    								let regExp = /\?\S*/g;
    								url += (regExp.test(url)) ? '&' + params.join('&') : '?' + params.join('&');
    							}
    							/**
    							 * 轻应用
    							 * 1.open_mode === 'CLIENT_BROWSER'，在客户端内部打开，否则用默认浏览器打开
    							 */
    							if (!app.isAdmin && app.app_kind === appsType.lightApp) {//轻应用
    								let openMode;
    								try {
    									openMode = app.bundles[0].settings.PC.open_mode;
    								} catch (e) {
    									openMode = app.bundles[0].open_mode;
    								}
    								if (openMode === 'CLIENT_BROWSER') {//客户端内部打开
    									// url = `http://172.16.1.74:5050/demo/demo.html`;
    									$rootScope.$emit('appDetailShow', {
    										from: 'service:AppMarket',
    										appDetailUrl: url,
    										appInfo: app
    									});
    									AppCategory.addAppToRecentlyUsed(userId, app, orgId);
    									handleAppOpenLog(app);
    									resolve();
    									return false;
    								}

    								// 新窗口打开应用
    								if (openMode.toUpperCase() === 'POP_BROWSER') {
    									const appBrowserData = {
    										orgId: orgId,
    										userId: userId,
    										appDetailUrl: url,
    										app: app,
    									};
    									const windowId = appBrowserUtils.createWindowId(orgId, userId, app.app_id);

    									if (appBrowserUtils.appBrowserIsOpened(windowId)) {
    										return;
    									}

    									appBrowserUtils.cacheAppInfo(windowId, appBrowserData);
    									appBrowserUtils.openAppBrowser(windowId);
    									AppCategory.addAppToRecentlyUsed(userId, app, orgId);
    									handleAppOpenLog(app);
    									resolve();
    									return false;
    								}
    							}
    							// 判断是否带有chrome打开标识
    							if (/[?|&]specify_browser=chrome/ig.test(url) && process.platform === 'win32') {
    								// 需要提前检测是否安装了 chrome
    								getWinChromePath(function(chromePath) {
    									if (!chromePath) {
    										Notification.showMessage('未安装chrome浏览器，请联系IT服务台', 'error');
    									} else {
    										require('opener')([chromePath, url], function(err) {
    											if (err) {
    												Notification.showMessage('未安装chrome浏览器，请联系IT服务台', 'error');
    												return;
    											}
    											AppCategory.addAppToRecentlyUsed(userId, app, orgId);
    											handleAppOpenLog(app);
    											resolve();
    										});
    									}
    								});
    							} else {
    								window.openUrl(url);//服务号管理+轻应用管理+轻应用非客户端
    								AppCategory.addAppToRecentlyUsed(userId, app, orgId);
    								handleAppOpenLog(app);
    								resolve();
    							}
    						})
    					})
    				}

    				function getWinChromePath(finisher) {
    					//const chromePath = process.cwd() + '\\ChromePortable\\App\\Chrome-bin\\chrome.exe';
    					const chromePath = process.cwd() + '\\ChromePortable\\ChromePortable.exe';
    					function tryLocation(p, callback) {
    						fs.exists(p, function(exists) {
    							if (exists) callback(true);
    							else callback(false);
    						});
    					};


    					tryLocation(chromePath, function(had) {
    						finisher && finisher(had ? chromePath : false);
    					});
    				};

    				/**
    				 * 关闭已在客户端内部打开的应用详情
    				 * @param {*} isRestore: 是否显示打开前的状态。为false时，直接显示应用列表 
    				 * @param {*} isAppInit: 是否应用初始化操作。为 true时，广播的事件需要包含不关闭 closeShadow 的操作
    				 */
    				function closeAppDetail(isRestore, isAppInit) { 
    					if (isRestore !== false) {
    						isRestore = true;
    					}

    					if (isAppInit !== true) {
    						isAppInit = false;
    					}

    					$rootScope.$broadcast('closeAppDetail', {
    						from: 'service:AppMarket', 
    						isRestore: isRestore, 
    						isAppInit: isAppInit
    					});
    				}
    				//
    				function openServeNoArticle(appId, orgId, url, app) {
    					Ticket.getTicket(AuthService.getToken(), orgId)
    						.then(function (data) {
    							let params = [],
    								userId = AuthService.currentUserId(),
    								appsType = AppCategory.getAppsType(), 
    								openExternal = false;

    							if (url.toLowerCase().indexOf(('open_mode=SYSTEM_BROWSER').toLowerCase()) > -1) {
    								openExternal = true;
    							}

    							if (url && url.indexOf('{{ticket}}') > -1) {
    								url = url.replace('{{ticket}}', data.result.ticket_id);
    							} else {
    								params.push('ticket=' + data.result.ticket_id);
    							}
    							params.push('user_id=' + userId);
    							params.push('domain_id=' + Constant.DOMAIN_ID);
    							params.push('org_id=' + orgId);
    							if (url && url.indexOf('{{username}}') > -1) {
    								url = url.replace('{{username}}', AuthService.currentUser().username);
    							} else {
    								params.push('username=' + AuthService.currentUser().username);
    							}
    							params.push('random=' + Date.now());

    							let regExp = /\?\S*/g;
    							/* 不判断 ticket 直接拼接几个固定的参数
    							if (url.indexOf('ticket') === -1) {
    								url += (regExp.test(url)) ? '&' + params.join('&') : '?' + params.join('&');
    							}
    							*/
    							url += (regExp.test(url)) ? '&' + params.join('&') : '?' + params.join('&');

    							if (url.substring(0, 4) != 'http' ) {
    								url = 'http://' + url;
    							}

    							if (openExternal) {
    								window.openUrl(url);
    							} else {
    								$rootScope.$emit('appDetailShow', {
    									from: 'service:AppMarket',
    									appDetailUrl: url,
    									appInfo: app
    								});
    							}

    						});
    				}
    				// 
    				let allApps = [];
    				function getAppDetail (app) {
    					let appDetail = angular.copy(app);
    					let allAppsCategories = AppCategory.getAllAppsCategories();
    					allAppsCategories.forEach(function (category) {
    						allApps = allApps.concat(category['apps']);
    					});
    					for (let i = 0, len = allApps.length; i < len; i++) {
    						if (allApps[i] && allApps[i]['app_id'] === app['app_id'] && allApps[i]['app_kind'] == app['app_kind']) {
    							appDetail = angular.copy(allApps[i]);
    							break;
    						}
    					}
    					return appDetail;
    				}
    				/**
    				 * 获取app后分类返回
    				 * @param {number} orgId 组织id
    				 * @param {string} app_kind app类型
    				 * @param {boolean} isAdmin 是否管理
    				 */
    				function classifyApps(orgId,app_kind,isAdmin,isGetNotify){
    					let apps = [];
    					return new Promise(function(resolve, reject){
    						Storage.getAppsByType(orgId,app_kind,isAdmin).then(function (data) {
    							if (data.length == 0) {//无app直接返回空数组
    								resolve([]); 
    							}else{
    								//用于寻找app小分类下标
    								function findIndex(categoryId) {
    									for (let i = 0; i < apps.length; i++) {
    										if (apps[i]['category_id'] == categoryId) {
    											return i;
    										}
    									}
    									return -1;
    								}
    								_.forEach(data,function(item,index){
    									let obj = {};
    									let key = findIndex(item.category_id);
    									/**
    									 * 1. 如果有小红点，获取之后再push
    									 * 2. 无小红点直接push
    									 */
    									if (isGetNotify && item.bundles && item.bundles.notify_url) {
    										Ticket.getTicket(AuthService.getToken(), item.org_id).then(function(data) {
    											if (data.status === Constant.SUCCESS) {
    												let url = item.bundles.notify_url +
    												'?tenantId='+ Constant.DOMAIN_ID +
    												'&domainId='+ Constant.DOMAIN_ID +
    												'&username=' + $rootScope.currentUser.username +
    												'&userId=' + $rootScope.currentUser.user_id + 
    												'&ticket=' + data.result.ticket_id +
    												'&orgId=' + item.org_id;
    												// let url = 'http://172.16.1.244/runtime/trackPoint?tenantId=atwork&domainId=atwork&username=13631834105&userId=5db38249c7ec40adad01e47a275b78c0&ticket=9fb0d3ef4bd44ff2a1c330b412b2cc63&orgId=fe8f88ec-4ec6-4881-96e0-93f6e64c3365'
    												$http.get(url).then(function (resp) {
    													item.tip = resp.data.tip;
    												}, function () {
    													console.log("app notifyurl error");
    												});
    											} else {
    												console.log('getTicket error:', item);
    											}
    										}, function(data) {
    											console.log('getTicket error:', item);
    										});
    									}
    									if(key > -1){
    										apps[key]['apps'].push(item);
    									}else{
    										obj['category_id'] = item.category_id;
    										obj['category_id'] = item.category_id;
    										obj['category_name'] = item.category;
    										obj['name'] = item.category;
    										obj['sort'] = item.category_sort;
    										obj['apps'] = [];
    										obj['apps'].push(item);
    										apps.push(obj);
    									}
    								})
    								resolve(apps);
    							}
    						},function(err){
    							console.log(err)
    							reject(err)
    						})
    					})
    				}

    				return {
    					openAppDetail: openAppDetail,
    					openServeNoArticle: openServeNoArticle,
    					closeAppDetail: closeAppDetail,
    					// setCurrentApp: setCurrentApp,
    					// getCurrentApp: getCurrentApp,
    					// updateAppInfo: updateAppInfo, 
    					getAppDetail: getAppDetail,
    					getAppMallCategory: getAppMallCategory,
    					getApps: getApps,
    					deleteApp: deleteApp,
    					addApp: addApp,
    					classifyApps: classifyApps,
    					getWinChromePath: getWinChromePath,

    					getHistoryMsgs: function (params) {
    						return new Promise(function (resolve, reject) {
    							appMarket.getHistoryMsgs({
    								org_code: params.orgCode,
    								app_id: params.appId,
    								access_token: AuthService.getToken(),
    								skip: params.skip || 0,
    								limit: params.limit || 20,
    							}).$promise
    							.then(function (data) {
    								console.log(`getHistoryMsgs:`, data);
    								if (data.status === Constant.SUCCESS) {
    									resolve(data.result);
    								} else {
    									reject(data);
    								}
    							})
    							.catch (function (err) {
    								reject(err);
    							});
    						});
    					}
    				};
    			}
    		]);
    })(angular);
    /**
     * 打开 app 详情逻辑
     * 1. 打开轻应用
     * 	1. app.bundles[0].settings.PC.open_mode === 'CLIENT_BROWSER'：PC 客户端打开
     * 	2. app.bundles[0].settings.PC.open_mode !== 'CLIENT_BROWSER'：操作系统默认浏览器打开
     * 2. 打开服务号
     * 	1. 会话窗口打开
     * 	2. 点击图文消息时，根据对应的消息 org_id 打开消息详情
     * 3. 打开轻应用管理
     * 	1. 操作系统默认浏览器打开链接：url += (regExp.test(url)) ? '&' + params.join('&') : '?' + params.join('&'),params包含ticket, user_id, domain_id, org_id, username
     * 4. 打开服务号管理
     * 	1. 操作系统默认浏览器打开链接：url += 'go?a=' + app.app_id + '&t=' + data.result.ticket_id
     */
    """

    # 输出content变量
    print(content)
    return content


def update_chrome_path(file_path, type, app_folder_exist):
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            content = file.read()

        # print(content)

        old_content = get_content()

        # if content == old_content:
        #     print("same")

        if type == "chrome92":
            updated_content = content.replace(
                '\\\\ChromePortable\\\\ChromePortable.exe',
                '\\\\ChromePortable\\\\App\\\\Chrome-bin\\\\chrome.exe'
            )
            with open(file_path, 'w', encoding='utf-8') as file:
                file.write(updated_content)
            print('找到92版本谷歌，进行文件处理...')
        else:
            if app_folder_exist == "true":
                updated_content = content.replace(
                    '\\\\ChromePortable\\\\App\\\\Chrome-bin\\\\chrome.exe',
                    '\\\\ChromePortable\\\\ChromePortable.exe'
                )
                with open(file_path, 'w', encoding='utf-8') as file:
                    file.write(updated_content)
                print('找到64版本谷歌, 由chrome.exe切换为ChromePortable.exe，进行文件处理...')
            else:
                if os.path.getsize(file_path) == 0:
                    updated_content = old_content
                    with open(file_path, 'w', encoding='utf-8') as file:
                        file.write(updated_content)
                    print('不存在92版本, 找到64版本谷歌，文件恢复...')

        print(f'文件 {file_path} 更新成功')
    except Exception as e:
        print(f'更新文件 {file_path} 失败，错误信息：{e}')

def main():
    folder_path = 'C:\\minjie\\minjie\\'
    app_folder_path = os.path.join(folder_path, 'ChromePortable\\App')
    app_bin_folder_path = os.path.join(folder_path, 'ChromePortable\\App\\Chrome-bin')
    target_file_path = os.path.join(folder_path, 'app\\scripts\\services\\app_market.service.js')

    app_folder_exist = "false"
    if os.path.exists(app_folder_path):
        app_folder_exist = "true"

    if os.path.exists(app_bin_folder_path):
        print('检测到存在92版本的谷歌，进行文件处理...')
        if os.path.exists(target_file_path):
            update_chrome_path(target_file_path, "chrome92", app_folder_exist)
        else:
            print(f'文件 {target_file_path} 不存在，处理失败')
    else:
        print('未检测到92版本的谷歌，进行文件处理...')
        if os.path.exists(target_file_path):
            update_chrome_path(target_file_path, "chrome64", app_folder_exist)
        else:
            print(f'文件 {target_file_path} 不存在，处理失败')

if __name__ == "__main__":
    main()
